//
//  GatewayManageController.m
//  YSSmartHome
//
//  Created by yanghao on 2016/10/20.
//  Copyright © 2016年 yahaong. All rights reserved.
//

#import "GatewayManageController.h"
#import "ConnectGatewayController.h"
#import "UIBarButtonItem+Extension.h"
#import "DataManager.h"
#import "XAIGateway.h"
#import "ZTDeviceUtil.h"
#import "MGSwipeTableCell.h"
#import "GatewayEditController.h"
#import "ZTLinkageUtil.h"
#import "JPUSHService.h"
#import "YSCommon.h"

static NSString *const kZTTableViewGatewayCellReuseIdentifier = @"kZTTableViewGatewayCellReuseIdentifier";
@interface GatewayManageController ()
<
UITableViewDelegate,
UITableViewDataSource,
DataManagerRefreshDelegate,
MGSwipeTableCellDelegate
>
@property (nonatomic, strong) UITableView *m_tableViewGateway;
@property (nonatomic, strong) NSArray *m_arrayGateways;
@end

@implementation GatewayManageController

#pragma mark - life cycle
- (void)dealloc
{
    debugLogInfo(@"GatewayManageController dealloc");
    [kDataManager removeGatewayRefreshDelegate:self];
}

- (void)viewDidLoad
{
    [super viewDidLoad];
    [self initSubviews];
    [kDataManager addGatewayRefreshDelegate:self];
    [self gatewayRefresh:kDataManager];
}
- (void)viewWillAppear:(BOOL)animated
{
    [super viewWillAppear:animated];
    [self.navigationController setNavigationBarHidden:NO animated:YES];
}
- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

#pragma mark - event response

- (void)didTappedSearchNewGateway
{
    ConnectGatewayController *connectGatewayVc = [[ConnectGatewayController alloc]init];
    [self.navigationController pushViewController:connectGatewayVc animated:YES];
}

#pragma mark - DataManagerRefreshDelegate

- (void)gatewayRefresh:(DataManager *)manager callbackType:(GatewayCallbackType)callbackType
{
    @synchronized (self)
    {
        NSMutableArray *gateways = [NSMutableArray array];
        ZTUser *user =  kMQTTSessionManager.currentUser;
        for (XAIGateway *gtw in manager.gatewayListenList)
        {
            if (gtw.apsn != user.currentBindApsn)
            {
                [gateways addObject:gtw];
            }
        }
        self.m_arrayGateways = gateways;
    }
    dispatch_async(dispatch_get_main_queue(), ^{
        [self.m_tableViewGateway reloadData];
    });

}
- (void)gatewayRefresh:(DataManager *)manager {
    NSMutableArray *gateways = [NSMutableArray array];
    ZTUser *user =  kMQTTSessionManager.currentUser;
    @synchronized (manager.gatewayListenList)
    {
        for (XAIGateway *gtw in manager.gatewayListenList)
        {
            if (gtw.apsn != user.currentBindApsn)
            {
                [gateways addObject:gtw];
            }
        }
        self.m_arrayGateways = gateways;
    }
    dispatch_async(dispatch_get_main_queue(), ^{
        [self.m_tableViewGateway reloadData];
    });

}

#pragma mark - UITableViewDataSource
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{
    return (self.m_arrayGateways.count > 0) ? 2 : 1;
}
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    if (0  == section)
    {
        return kMQTTSessionManager.currentGateway ? 1 : 0;
    }
    else if (1 == section)
    {
        return self.m_arrayGateways.count;
    }
    return 0;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    MGSwipeTableCell *cell = [tableView dequeueReusableCellWithIdentifier:kZTTableViewGatewayCellReuseIdentifier];
    cell.textLabel.font = [UIFont systemFontOfSize:15];
    if (0 == indexPath.section)
    {
        XAIGateway* gateway = kMQTTSessionManager.currentGateway;
        debugLogInfo(@"currentGateway name = %@",gateway.name);
        cell.textLabel.text = gateway.name;
        cell.imageView.hidden = NO;
    }
    else if (1 == indexPath.section)
    {
        XAIGateway *gateway = self.m_arrayGateways[indexPath.row];
        cell.textLabel.text = gateway.name;
        cell.imageView.hidden = YES;
    }
    cell.imageView.image = [UIImage imageNamed:@"scene_date_selected"];
    cell.rightButtons = [self createRightButtons:2];
    cell.delegate = self;
    return cell;
}

#pragma mark - MGSwipeTableCellDelegate
-(BOOL)swipeTableCell:(MGSwipeTableCell*) cell tappedButtonAtIndex:(NSInteger) index direction:(MGSwipeDirection)direction fromExpansion:(BOOL) fromExpansion
{
    debugLogInfo(@"Delegate: button tapped, %@ position, index %d, from Expansion: %@",
          direction == MGSwipeDirectionLeftToRight ? @"left" : @"right", (int)index, fromExpansion ? @"YES" : @"NO");
    if (direction == MGSwipeDirectionRightToLeft && index == 0)
    {
        NSIndexPath * path = [self.m_tableViewGateway indexPathForCell:cell];
        if (path.section == 0) {
            [kMQTTSessionManager.currentGateway unbind];
            
        }else {
            XAIGateway *gateway = self.m_arrayGateways[path.row];
            [gateway unbind];
        }
        return NO;
    }
    else if(direction == MGSwipeDirectionRightToLeft && index == 1)
    {
        //edit button
        NSIndexPath * path = [self.m_tableViewGateway indexPathForCell:cell];
        GatewayEditController *gatewayVC = [[GatewayEditController alloc]init];
        if (path.section == 0) {
            gatewayVC.gateway = kMQTTSessionManager.currentGateway;
        }else {
            XAIGateway *gateway = self.m_arrayGateways[path.row];
            gatewayVC.gateway = gateway;
        }
        [self.navigationController pushViewController:gatewayVC animated:YES];
        return NO;
    }
    return YES;
}

#pragma mark - UITableViewDelegate

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    if (1 == indexPath.section)
    {
        XAIGateway *gateway = self.m_arrayGateways[indexPath.row];
        kMQTTSessionManager.currentUser.currentBindApsn = gateway.apsn;
        [kMQTTSessionManager.currentUser archiver];
        kMQTTSessionManager.currentGateway = gateway;
        [[NSNotificationCenter defaultCenter]postNotificationName:kZTSwitchGatewayNotifKey object:nil];
        [self gatewayRefresh:kDataManager];
    }
}


- (NSString *)tableView:(UITableView *)tableView titleForHeaderInSection:(NSInteger)section
{
    if (0 == section)
    {
        return @"当下连接网关";
    }else if (1 == section)
    {
        return @"点击切换其他网关";
    }
    return nil;
}
- (CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section
{
    if (0 == section || 1 == section) {
        return 30;
    }
    return 0;
}
-  (CGFloat)tableView:(UITableView *)tableView heightForFooterInSection:(NSInteger)section
{
    return 0;
}

//- (void)findAllDevWithGateway:(XAIGateway *)gateway
//{
//    [gateway getGatewayStatus];
//    [ZTDeviceUtil findAllDevWithApsn:gateway.apsn];
//    
//}
#pragma mark - private method

- (void)initSubviews{
    [self initNavigationView];
    [self.view addSubview:self.m_tableViewGateway];
    [self.m_tableViewGateway mas_makeConstraints:^(MASConstraintMaker *make) {
        make.bottom.trailing.leading.top.equalTo(self.view);
    }];
}
- (void)initNavigationView
{
    self.navigationItem.title = @"网关管理";
    self.navigationItem.rightBarButtonItem = [UIBarButtonItem createBarbuttonItem:@"security_icon_search" target:self action:@selector(didTappedSearchNewGateway)];
}
-(NSArray *)createRightButtons: (int)number
{
    NSMutableArray * result = [NSMutableArray array];
    NSArray *colors = @[RGBColor(239, 75, 58),RGBColor(204, 204, 204)];
    NSArray *icons = @[[UIImage imageNamed:@"scene_bigdel"], [UIImage imageNamed:@"scene_bigedit"]];
    for (int i = 0; i < number; ++i)
    {
        MGSwipeButton * button = [MGSwipeButton buttonWithTitle:@"" icon:[icons objectAtIndex:i] backgroundColor:[colors objectAtIndex:i]  padding:15 callback:^BOOL(MGSwipeTableCell * sender){
            debugLogInfo(@"Convenience callback received (left).");
            return YES;
        }];
        [result addObject:button];
    }
    return result;
}
#pragma mark - getters & setters
- (UITableView *)m_tableViewGateway
{
    if (!_m_tableViewGateway) {
        _m_tableViewGateway = [[UITableView alloc]initWithFrame:CGRectZero style:UITableViewStyleGrouped];
        _m_tableViewGateway.backgroundColor = kBgColor;
        _m_tableViewGateway.delegate = self;
        _m_tableViewGateway.dataSource = self;
        _m_tableViewGateway.showsVerticalScrollIndicator = NO;
        _m_tableViewGateway.showsHorizontalScrollIndicator= NO;
        _m_tableViewGateway.rowHeight = kIphoneSize_Height(52);
        _m_tableViewGateway.sectionFooterHeight = 0;
        [_m_tableViewGateway registerClass:[MGSwipeTableCell class] forCellReuseIdentifier:kZTTableViewGatewayCellReuseIdentifier];
        UIView *footerView = [[UIView alloc]init];
        _m_tableViewGateway.tableFooterView = footerView;
    }
    return _m_tableViewGateway;
}
@end
